<template>
  <div class="login-container">
    <h1>用户登录</h1>
    <div v-if="message" :class="['alert', messageType]">
      {{ message }}
    </div>
    <form @submit.prevent="handleLogin" class="login-form">
      <div class="form-group">
        <label for="username">用户名</label>
        <input 
          type="text" 
          id="username" 
          v-model="username" 
          required 
          placeholder="请输入用户名"
        />
      </div>
      <div class="form-group">
        <label for="password">密码</label>
        <input 
          type="password" 
          id="password" 
          v-model="password" 
          required 
          placeholder="请输入密码"
        />
      </div>
      <button type="submit" :disabled="loading">{{ loading ? '登录中...' : '登录' }}</button>
    </form>
    <div v-if="user" class="user-info">
      <h2>欢迎回来，{{ user.username }}!</h2>
      <button @click="handleLogout" class="logout-btn">退出登录</button>
    </div>
  </div>
</template>

<script>
import { ref } from 'vue'
import axios from 'axios'

export default {
  name: 'LoginComponent',
  setup() {
    const username = ref('')
    const password = ref('')
    const loading = ref(false)
    const message = ref('')
    const messageType = ref('')
    const user = ref(null)
    
    // 检查是否已登录
    const checkAuth = async () => {
      const token = localStorage.getItem('token')
      if (token) {
        try {
          const res = await axios.get('/api/user', {
            headers: {
              'x-auth-token': token
            }
          })
          user.value = res.data
        } catch (err) {
          localStorage.removeItem('token')
        }
      }
    }
    
    // 页面加载时检查登录状态
    checkAuth()
    
    const handleLogin = async () => {
      loading.value = true
      message.value = ''
      
      try {
        const res = await axios.post('/api/login', {
          username: username.value,
          password: password.value
        })
        
        // 保存 token 到本地存储
        localStorage.setItem('token', res.data.token)
        
        // 获取用户信息
        await checkAuth()
        
        message.value = '登录成功!'
        messageType.value = 'success'
        
        // 清空表单
        username.value = ''
        password.value = ''
      } catch (err) {
        console.error('登录错误:', err)
        message.value = err.response?.data?.msg || '登录失败，请检查用户名和密码'
        messageType.value = 'error'
        localStorage.removeItem('token')
      } finally {
        loading.value = false
      }
    }
    
    const handleLogout = () => {
      localStorage.removeItem('token')
      user.value = null
      message.value = '已退出登录'
      messageType.value = 'info'
    }
    
    return {
      username,
      password,
      loading,
      message,
      messageType,
      user,
      handleLogin,
      handleLogout
    }
  }
}
</script>

<style>
.login-container {
  max-width: 400px;
  margin: 0 auto;
  padding: 2rem;
  border: 1px solid #ddd;
  border-radius: 8px;
  box-shadow: 0 2px 10px rgba(0, 0, 0, 0.1);
}

.login-form {
  display: flex;
  flex-direction: column;
  gap: 1rem;
}

.form-group {
  display: flex;
  flex-direction: column;
  gap: 0.5rem;
}

label {
  font-weight: bold;
}

input {
  padding: 0.75rem;
  border: 1px solid #ddd;
  border-radius: 4px;
  font-size: 1rem;
}

button {
  padding: 0.75rem;
  background-color: #4CAF50;
  color: white;
  border: none;
  border-radius: 4px;
  cursor: pointer;
  font-size: 1rem;
  transition: background-color 0.3s;
}

button:hover {
  background-color: #45a049;
}

button:disabled {
  background-color: #cccccc;
  cursor: not-allowed;
}

.alert {
  padding: 0.75rem;
  margin-bottom: 1rem;
  border-radius: 4px;
}

.success {
  background-color: #d4edda;
  color: #155724;
  border: 1px solid #c3e6cb;
}

.error {
  background-color: #f8d7da;
  color: #721c24;
  border: 1px solid #f5c6cb;
}

.info {
  background-color: #d1ecf1;
  color: #0c5460;
  border: 1px solid #bee5eb;
}

.user-info {
  margin-top: 2rem;
  padding: 1rem;
  background-color: #f8f9fa;
  border-radius: 4px;
  text-align: center;
}

.logout-btn {
  background-color: #dc3545;
  margin-top: 1rem;
}

.logout-btn:hover {
  background-color: #c82333;
}
</style>